<template>
  <div class="queue-wrap">
    <continer :showPage="showPage" :isNoTabs="true">
      <template slot="search">
        <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryList"></QuickSearch>
      </template>
      <template slot="oprate">
        <commonFilter
          :filterType="3"
          :filterFieldList="filterFieldList"
          @common-filter="filterSearch"
        ></commonFilter>
        <!-- <conditionFilter :filterFieldList="filterFieldList" @search="ordinaryFilterSearch" @search-close="filterSearchClose" ref='conditionFilterRef' class="margin-l-16 condition-filter"></conditionFilter> -->
        <el-button type="primary" size="mini" class="search-btn" @click="queryList">查询</el-button>
      </template>
      <template slot="content">
        <instiutionTable ref="tableRef"
                         class="instiutionTable"
                         :pages="queueTablePages"
                         :instiutionTableData="queueTableData"
                         :instiutionTableHeader="queueTableHeader"
                         :isCustomerCol="true"
                         :customerTableHeader="customerTableHeader"
                         @headrChange="handleHeaderChange"
                         @batchClick="batchClick"
                         @sizeChange="sizeChange"
                         @currentChange="currentChangeFun">
                         <template #source="{ scope }">
                           {{ sourceMap[scope.row.source] }}
                         </template>
          <template #orderStatus="{ scope }">
            <span class="order-status" :style="{border: '1px solid ' + orderStatusMap[scope.row.orderStatus].color, color: orderStatusMap[scope.row.orderStatus].color}">{{ orderStatusMap[scope.row.orderStatus].name }}</span>
          </template>
          <template #currentSlaStatus="{ scope }">
            <div>
              <span :class="{overtime: scope.row.currentSlaStatus === 1, noovertime: scope.row.currentSlaStatus === 2, unmatch: scope.row.currentSlaStatus === 3}">{{slaMap[scope.row.currentSlaStatus]}}</span>
            </div>
          </template>
          <template #entireSlaStatus="{ scope }">
            <div>
              <span :class="{overtime: scope.row.entireSlaStatus === 1, noovertime: scope.row.entireSlaStatus === 2, unmatch: scope.row.entireSlaStatus === 3}">{{slaMap[scope.row.entireSlaStatus]}}</span>
            </div>
          </template>
        </instiutionTable>
      </template>
      <template slot="page">
        <editBusiness :checkRead="false" @success="queryList" :agentList="agentListArr" @saveFun="saveFun" @cancelFun="back" ref="addOrEditBusinessRef" @pageBack="pageBack"></editBusiness>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Mixins } from 'vue-property-decorator'
import { deepClone, commonAction, checkHideTel } from '@/utils/common'
import { checkPermission } from '@/utils/directive'
import { CommonModule } from '@/store/modules/common'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import editBusiness from '../../components/editBusiness.vue'
import { handleList } from '../../utils/staticData'
import { businessStore } from '../../store/business'
import conditionFilter from '@/afterSales/components/conditionFilter/index.vue'
import workerOrder from '@/afterSales/views/business/mixins/workerOrder'
import cloneDeep from 'lodash/cloneDeep';
import { emitter } from '@/afterSales/utils/mmit';
import commonFilter from '@/afterSales/components/commonFilter/commonFilter.vue'

@Component({
  name: 'busUpcoming',
  components: {
    conditionFilter,
    QuickSearch,
    instiutionTable,
    editBusiness,
    continer,
    commonFilter
  }
})
export default class Queue extends Mixins(workerOrder) {
  [x: string]: any
  private showPage: boolean = false
  @Ref() private readonly addOrEditBusinessRef !: editBusiness
  @Ref() private readonly tableRef !: instiutionTable
  private cacheFilter: any[] = [];
  private filterFieldList = Object.freeze(handleList)
  private quickSearchForm = {
    form: {
      orderNo: '',
      customerNameOrPhone: '',
      customerContactPhone: ''
    },
    advSearchOptions: [
      { label: '工单编号', inputType: 'input', placeholder: '请输入工单编号', name: 'orderNo' },
      { label: '客户名称/手机号', inputType: 'input', placeholder: '请输入客户名称/手机号', name: 'customerNameOrPhone' },
      { label: '客户联系人手机号', inputType: 'input', placeholder: '请输入联系人手机号', name: 'customerContactPhone' }
    ]
  }

  private isListened = false

  // private batchOperate = [ // 批量操作设置
  //   { name: '批量删除', action: 'batchDelAgentFun', type: 'business', _id: 'skillGroup_management_delete' }
  // ]

  private title = ''

  private queueTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private queueTableData = []

  private slaMap: any = {
    1: '已超时',
    2: '未超时',
    3: '未匹配'
  }

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ key: agents[i]._id, label: agents[i].name })
    }
    return agentsArr
  }

  private get busCategoryMap () {
    const obj = {}
    businessStore.busCategory.map(item => {
      obj[item.id] = item.modelName
    })
    return obj
  }

  // private filterSearchClose () {
  //   this.cacheFilter = {};
  // }

  private ordinaryFilterSearch (data) {
    this.filterSearch(data);
  }

  private filterSearch (data) {
    this.cacheFilter = cloneDeep(data);
    this.currentChangeFun(1);
  }

  private pageBack () {
    this.showPage = false
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private sizeChange (size: number) {
    this.queueTablePages.pageSize = size
    this.queryList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.queueTablePages.current = page
    this.queryList()
  }

  private handleEdit (obj: any) { // 修改技能组
    this.showPage = true
    this.$nextTick(() => {
      this.addOrEditBusinessRef.getBusinessDataById(obj)
    })
  }

  private handleReceive (obj: any) {
    commonAction({
      url: '/server-flow/action/task/claim',
      method: 'post',
      data: { workModelOrderId: obj.orderId, workModelId: obj.modelId, activityName: obj.activityName, activityId: obj.activityId }
    }).then(res => {
      if (res.success) {
        this.$message.success('领取工单成功')
        this.queryList()
      }
    })
  }

  private batchDelAgentFun (selectedArr: any) { // 批量删除
    this.$confirm('确定要批量删除工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let sendData = {}
      if (typeof selectedArr === 'object') { // 单个操作，传ids
        sendData = { deleteDtoList: selectedArr || [] }
      } else { // 全选传查询条件
        sendData = { page: { pageNumber: this.queueTablePages.current, pageSize: this.queueTablePages.pageSize }, ...this.quickSearchForm.form }
      }
      commonAction({
        url: '/server-work/action/workOrder/batch/delete',
        method: 'post',
        data: sendData
      }).then(res => {
        if (res.success) {
          this.$message.success('批量删除工单成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryList()
        }
      })
    })
  }

  private saveFun (type) {
    this.queryList(type)
    this.back()
  }

  private queryList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.queueTablePages.current = 1
    }
    const params = {
      checkRead: false,
      listMeType: 3,
      filters: this.cacheFilter,
      page: {
        pageNumber: this.queueTablePages.current,
        pageSize: this.queueTablePages.pageSize
      },
      ...this.quickSearchForm.form
    }
    commonAction({
      url: '/server-work/action/workOrder/list',
      method: 'post',
      data: { ...params }
    }).then(res => {
      if (res.success) {
        const list = res.data.workOrderList || []
        const total = res.data.page.total
        if (list.length === 0) {
          const page = Math.ceil(total / this.queueTablePages.pageSize)
          if (!total) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.queueTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.queueTablePages.current = page
            this.queryList()
            return false
          }
        }
        console.log(CommonModule.publicCache.userListObj)
        list.forEach(item => {
          if (item.contactPhoneVO) {
            item.contactPhoneVO = ((item.contactPhoneVO.split(',')).map(v => checkHideTel(v))).join('、')
          }
          if (item.customerPhoneVO) {
            item.customerPhoneVO = ((item.customerPhoneVO.split(',')).map(v => checkHideTel(v))).join('、')
          }
          const agentObj = item.createUser && deepClone(CommonModule.publicCache.userListObj)[item.createUser]
          item.createUser = item.createUserName || (agentObj ? agentObj.name : '--')
        })
        this.queueTableData = list
        this.queueTablePages.total = total
      }
    })
  }

  private back () {
    this.$nextTick(() => {
      // this.addOrEditBusinessRef.setQueueData()
      this.showPage = false
    })
  }

  private activated () {
    // console.log('activated')
  }

  private workorderNotice (data: any) {
    this.isListened = true
    console.log(data)
    this.handleEdit(data)
  }

  private beforeRouteEnter (to: any, from: any, next: any): void {
    next((vm) => {
      vm.showPage = false
      vm.queryList()
      if (to.params && to.params.modelId && to.params.orderId) {
        vm.handleEdit(to.params)
      }
      if (to.query && to.query.modelId && to.query.orderId) {
        vm.handleEdit(to.query)
      }
    })
  }

  private destroyed () {
    emitter.off('workorderNotice', this.workorderNotice);
  }

  private created () {
    emitter.on('workorderNotice', this.workorderNotice);
  }

  public handleHeaderChange (val) {
    const row = val.filter(item => {
      return item.prop
    }).map(item => {
      return {
        businessId: item.prop,
        isShow: item.show ? 1 : 0
      }
    })
    if (this.originColId) {
      commonAction({
        url: '/server-work/action/view/update',
        method: 'post',
        data: { columnType: this.columnType, showRow: row, id: this.originColId }
      }).then(res => {
        if (!res.success) {
          this.$message.error(res.message)
        }
      })
    }
    this.queueTableHeader = val.filter(item => item.show)
    // 处理操作列
    const handlers: any[] = []
    handlers.push({ name: '查看', handleFn: (scope: any) => this.handleEdit(scope.row) })
    this.queueTableHeader.push({ label: '操作', width: 100, handlers })
    this.queryList()

  }

  private beforeMount () {
    this.getColumn(3)
  }
}
</script>

<style lang="stylus" scoped>
.search-btn {
  margin: 0px 10px
}
.queue-wrap
  width 100%
  height 100%
  position relative
.instiutionTable
  .overtime
    color: #FC6B5C
    border 1px solid #FC6B5C
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500
  .noovertime
    color: #2ED47A
    border 1px solid #2ED47A
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500
  .unmatch
    color: #B3B9C7
    border 1px solid #B3B9C7
    padding: 2px 4px;
    border-radius: 4px;
    font-weight: 500
.order-status {
  border-radius: 4px;
  border: 1px solid #B3B9C7;
  color: #B3B9C7
  padding: 1px 8px;
  font-size: 12px;
  line-height: 14px;
  height: 20px;
}
</style>
